package com.andy.blog.common.utils.http;

import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Http请求工具
 * Created by andy on 2024/6/25 16:49
 **/
public class OkHttpUtils {

    private OkHttpUtils() {
    }

    private static final long KEEP_ALIVE_DURATION = 3L; // 连接保持活跃的时间，单位分钟
    private static final int MAX_IDLE_CONNECTIONS = 10; // 最大空闲连接数

    private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES))
            .build();


    /**
     * 发送GET请求
     * @param url 请求的URL
     * @return 响应体的字符串内容
     * @throws IOException 网络请求异常
     */
    public static String sendGet(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 发送POST请求（JSON格式）
     * @param url 请求的URL
     * @param jsonRequestBody JSON格式的请求体
     * @return 响应体的字符串内容
     * @throws IOException 网络请求异常
     */
    public static String postJson(String url, String jsonRequestBody) throws IOException {
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonRequestBody);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }
}
